package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:21:44
 */
public class HotCode031 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        HotCode031 hotCode = new HotCode031();
        hotCode.reverseKGroup(head, 2);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        List<ListNode> list = new ArrayList<>();
        ListNode index = head;
        while (index != null) {
            list.addLast(index);
            index = index.next;
        }
        int left = 0, right = k - 1, indexLeft, indexRight;
        while (right < list.size()) {
            indexLeft = left;
            indexRight = right;
            while (indexLeft < indexRight) {
                ListNode temp = list.get(indexRight);
                list.set(indexRight, list.get(indexLeft));
                list.set(indexLeft, temp);
                indexLeft++;
                indexRight--;
            }
            left = right + 1;
            right = left + k - 1;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).next = list.get(i + 1);
        }
        list.getLast().next = null;
        return list.getFirst();
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
